package com.xsomnus.open.imv2.foo.server.handler;

import com.xsomnus.open.imv2.protocol.request.QuitGroupRequestPacket;
import com.xsomnus.open.imv2.protocol.response.QuitGroupResponsePacket;
import com.xsomnus.open.imv2.util.SessionUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;

/**
 * @author @xsomnus666_xiawenye★
 * @since 2019/4/26 0026 10:50
 * 当你发现自己的才华撑不起野心时，就请安静下来学习吧
 */
public class QuitGroupRequestHandler extends SimpleChannelInboundHandler<QuitGroupRequestPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, QuitGroupRequestPacket msg) throws Exception {

        String groupId = msg.getGroupId();
        ChannelGroup channelGroup = SessionUtil.getChannelGroup(groupId);
        QuitGroupResponsePacket quitGroupResponsePacket = new QuitGroupResponsePacket();
        quitGroupResponsePacket.setGroupId(groupId);
        if (channelGroup != null) {
            quitGroupResponsePacket.setSuccess(true);
            channelGroup.remove(ctx.channel());
        } else {
            quitGroupResponsePacket.setSuccess(false);
            quitGroupResponsePacket.setReason("群聊[" + groupId + "]不存在");
        }
        ctx.channel().writeAndFlush(quitGroupResponsePacket);
    }
}
